<template>
	<view class="main">
		<view class="login-top">
			<image src="https://xgr.oss-cn-hangzhou.aliyuncs.com/icon/icon/logo.png" ></image>
		</view>
		<view class="v-box6">
			<block v-if="istel==false">
				<view class="xieyi dis-row">
					<view class="checkbox" >
						<checkbox-group @change="checkRideo">
							<label style="padding-right: 0;">
								<checkbox style="transform:scale(0.7)" value="cn" :checked="isgreen" />
							</label>
						</checkbox-group>
					</view>
					同意
					<text @click="openDoc(1)">《用户协议》</text>和
					<text @click="openDoc(2)">《隐私协议》</text>
				</view>
				<!-- #ifdef MP-WEIXIN -->
				<view class="login-btn">
					<!-- <button style=" background: #0575FF; color: #fff;" plain="true"
						@click="weixinLogin">手机号快捷登录</button> -->
					<button style=" background: #0575FF; color: #fff; font-size: 28rpx;" open-type="getPhoneNumber"
						@getphonenumber="getPhoneNumber" class="ft1">授权获取手机号码</button>	
				</view>
				<!-- #endif -->
				<!-- #ifdef MP-ALIPAY || APP-PLUS -->
				<view class="login-btn" v-if="istel==false">
					<button style=" background: #0575FF; color: #fff;" plain="true"
						@click="APPweixinLogin">手机号快捷登录</button>
				</view>
				<!-- #endif -->
			</block>
			<block v-if="istel==true">
				<button style=" background: #0575FF; color: #fff; font-size: 28rpx;" open-type="getPhoneNumber"
					@getphonenumber="getPhoneNumber" class="ft1">授权获取手机号码</button>
			</block>

				
		
		</view>
<view style="width: 100%; display: flex; justify-content: center; margin-top: 30rpx;" @click="urlback()">
					<text style="color: gray;text-decoration: underline;">暂不登录</text>
				</view>
	</view>
</template>

<script>
	import Index from "@/common/index-model.js"
	let index = new Index()
	let that = null
	export default {
		data() {
			return {
				istel: false,
				value: '',
				loginFrom: {
					// phone:'18066742510',
					phone: '',
					code: ''
				},
				logBtn: true,
				codemsg: '获取验证码',
				sendDataShow: true,
				sendData: 60,
				phonecheckmsg: '',
				isphone: true,
				iscode: true,
				codecheckmsg: '',
				modetel: '',
				wxback: {
					code: '',
					type: '',
					uid: '',
					checkCode: '',
					inviteCode:''
				},
				isgreen: false,
				backUrl: '',
				jobid: '',
				sourceUrl: '',
				currentCity: {},
				deviceId: '',
			}
		},
		methods: {
			urlback(){
				index.navigate_back();
			},
			checkRideo(e) {
				console.log('是否选中---', e, this.isgreen)
				if (e.detail.value.length == 0) {
					this.isgreen = false
				} else {
					this.isgreen = true
				}
			},
			openDoc(type) {
				index.navigate_to('./xieyi?type=' + type)
			},
			//获取当前地图的经纬度
			
			getPhoneNumber(e) {
				if (this.isgreen == false) {
					index.show_tips('请先同意用户协议和隐私协议')
					return false
				}
				console.log('--getPhoneNumber---',e);
				if(!e.detail.encryptedData){
					index.show_tips('登陆失败')
					return false
					
				}
				
				uni.login({
					provider: 'tianxiagognren',
					success: (wxres) => {
						let sendpost = {
							"code": wxres.code,
							"type": "WECHAT_MINI"
						}
						this.wxback.code = wxres.code
						this.wxback.type = "WECHAT_MINI"
						console.log('获取手机号登录----',sendpost)
						index.getPublicMember(sendpost, 'client/third/auth/loginByCode',
							'post', res => {
								this.wxback.code = e.detail.code
								 console.log('--当前页面路径---',res);
								if (res.data.code == 200) {
									uni.setStorageSync('token', res.data.result.token);
									uni.setStorageSync('userid', res.data.result.userId);
									
									index.show_tips(res.data.message)
									
									var pages = getCurrentPages();
									var page = pages[pages.length-2];
									console.log('===============================', pages,page);
									if(page !=undefined ){
										uni.navigateBack();
									}else{
										setTimeout(() => {
											index.switch_tab('../../pages/index/index')
										}, 2000)
									}
								} else {
				
									if (res.data.code == '400000') {
										this.wxback.uid = res.data.result.uid
										this.wxback.checkCode = res.data.result
											.checkCode
										// this.istel = true;
										// uni.hideLoading();
										this.bindMobile()
										// index.redirectto('./wxlogin?uid='+res.data.result.uid+"&checkCode="+res.data.result.checkCode);
									} else {
										index.show_tips(res.data.message)
										return false;
									}
								}
							})
				
					},
					fail: (err) => {
						console.log(err, '===登录失败=====')
					}
				})
			},
			bindMobile(){
				console.log('绑定手机号====',this.wxback)
				if (uni.getStorageSync('shareUserId')) {
					let inviteCode = {
						userId: uni.getStorageSync('shareUserId')
					}
					this.wxback.inviteCode = JSON.stringify(inviteCode);
				}
				index.getPublicMember(this.wxback, '/client/third/auth/bindMiniMobile', 'post', res => {
					console.log('绑定手机号结果====',res,res.data.result.token)
					if (res.data.code == 200) {
						uni.setStorageSync('token', res.data.result.token);
						uni.setStorageSync('userid', res.data.result.userId);
						if(res.data.result.inviteUserId){
							console.log("有inviteUserId")
							uni.setStorageSync('userid', res.data.result.inviteUserId);
						}
						index.show_tips(res.data.message)
						// uni.setStorageSync('token',res.data.result.token);
						// this.getHxUser();
						setTimeout(()=>{
							uni.navigateBack();
						},2000)
					}
				})
			},
			closeTelTime() {
				this.istel = false
			},
			weixinLogin() {
				console.log('微信登录-------------')
				uni.showLoading({
					title: '登录中,请稍后'
				});
				if (this.isgreen == false) {
					index.show_tips('请先同意用户协议和隐私协议')
					return false
				}

				uni.getUserProfile({
					provider: 'weixinlogin',
					desc: "小程序授权登录",
					success: (wx) => {
						console.log(wx);
						let tempUser = {
							'encryptedData': wx.encryptedData,
							'userinfo': wx.userInfo
						}
						uni.login({
							provider: 'tianxiagognren',
							success: (wxres) => {
								let sendpost = {
									"code": wxres.code,
									"type": "WECHAT_MINI"
								}
								this.wxback.code = wxres.code
								this.wxback.type = "WECHAT_MINI"
								index.getPublicMember(sendpost, 'client/third/auth/loginByCode',
									'post', res => {
										if ((res.data.code == 200) && res.data.success) {
											index.show_tips(res.data.message)

											uni.setStorageSync('token', res.data.result.token);
											uni.setStorageSync('userid', res.data.result
												.userId);

											this.$nextTick(() => {
												this.getHxUser();
											})
											// console.log('--当前页面路径---',self.sourceUrl) this.sourceUrl=='pages/index/index' ||
											if (this.sourceUrl == 'pages/worker/index' ||
												this.sourceUrl == 'pages/entertainment/index' ||
												this.sourceUrl == 'pages/message/index' ||
												this.sourceUrl == 'pages/user/index'
											) {
												setTimeout(() => {
													index.switch_tab('/' + this
														.sourceUrl);
												}, 2000)
											} else {
												setTimeout(() => {
													index.navigate_back();
												}, 2000)
											}
										} else {

											if (res.data.code == '400000') {
												this.wxback.uid = res.data.result.uid
												this.wxback.checkCode = res.data.result
													.checkCode
												this.istel = true;
												uni.hideLoading();
												//index.redirectto('./wxlogin?uid='+res.data.result.uid+"&checkCode="+res.data.result.checkCode);
											} else {
												index.show_tips(res.data.message)
												return false;
											}
										}
									})

							},
							fail: (err) => {
								console.log(err, '===登录失败=====')
							}
						})
					},
					fail(e) {
						console.log(e, '555555555555555');
					}
				})
			},
			APPweixinLogin() {
				that = this
				uni.getProvider({
					service: 'oauth',
					success: function(res) {
						if (res.provider.indexOf('weixin') == -1) {
							index.show_tips('您没有安装微信')
							return false
						}
						uni.login({
							provider: 'weixin',
							onlyAuthorize: true,
							success: function(wxlog) {
								let wxsend = {
									"code": wxlog.code,
									"type": "WECHAT",
									// "rid":3
								}
								console.log(wxsend, '====wxsend===')
								index.getPublicMember(wxsend, 'client/third/auth/loginByCode',
									'post', bacres => {
										if (bacres.data.code == 200 && bacres.data.success) {
											console.log(bacres)
										} else if (bacres.data.code == '400000') {
											index.show_tips(bacres.data.message)
											that.istel = true
										}
									})
								// uni.getUserInfo({
								//  provider: 'weixin',
								//  success: (wxuser) => {
								//  	  console.log(wxuser,'======wxuser======')
								//  }
								// })
							}
						})
					}
				});
			},
			closeTelTimeSure() {
				let send = {
					"mobile": this.modetel,
					"uid": this.wxback.uid,
					"checkCode": this.wxback.checkCode,
					"type": this.wxback.type
				}
				if (this.isgreen == false) {
					index.show_tips('请先同意用户协议和隐私协议')
					return false
				}
				index.getPublicMember(send, 'client/third/auth/bindMobile', 'post', res => {
					if (res.data.code == 200 && res.data.success) {
						index.show_tips(res.data.message)
						uni.setStorageSync('token', res.data.result.token);
						//uni.setStorageSync('userid',res.data.result.token);
						this.getHxUser();
						//uni.navigateBack();
						setTimeout(() => {
							index.switch_tab('../../pages/index/index')
						}, 2000)
					} else {
						index.show_tips(res.data.message)
						return false
					}
				})
			},
			codeEnd(e) {
				let codes = this.loginFrom.code;
				if (index.is_code_number(codes) && index.is_phone_number(this.loginFrom.phone)) {
					this.logBtn = false;
				} else {
					this.logBtn = true;
				}
			},
			sendlogin() {
				if (!index.is_phone_number(this.loginFrom.phone)) {
					this.phonecheckmsg = '请输入正确的手机号码'
					this.isphone = false
				} else {
					this.isphone = true
				}
				if (!index.is_code_number(this.loginFrom.code)) {
					this.codecheckmsg = '请输入正确的验证码'
					this.iscode = false
				} else {
					this.iscode = true
				}
				uni.showLoading({
					title: '登录中,请稍后'
				});
				let sendPost = {
					"mobile": this.loginFrom.phone,
					"code": this.loginFrom.code
				}
				index.getPublicMember(sendPost, '/sys/mobileLogin', 'post', res => {
					if (res.data.code == 200) {
						index.show_tips(res.data.message)
						uni.setStorageSync('token', res.data.result.token);
						uni.setStorageSync('userid', res.data.result.userId);
						this.getHxUser();
						//uni.navigateBack();
						setTimeout(() => {
							index.switch_tab('../../pages/index/index')
						}, 2000)

					} else {
						index.show_tips(res.data.message)
						return false
					}
				})
			},
			getHxUser() {
				index.getPublicUserMember({}, '/client/public/select/user', 'get', res => {
					console.log(res);
					if (res.data.code == 200) {
						this.loginHx(res.data.result);
					}
				})
			},
			loginHx(data) {
				var options = {
					user: data.hxname,
					pwd: data.hxPassword_,
					appKey: this.$WebIM.config.appkey,
					success: function(res) {
						// getApp().globalData.conn.open({
						// 	user: data.hxname,
						// 	accessToken: res.access_token,
						// });
						uni.setStorageSync('hxuser', data.hxname);
						uni.setStorageSync('hxpass', data.hxPassword_);
						uni.setStorageSync('hxtoken', res.access_token);
					},
					error: function() {

					}
				};
				this.$WebIM.conn.open(options);
			},
			getCode() {
				if (!index.is_phone_number(this.loginFrom.phone)) {
					index.show_tips('请输入正确的手机号码')
					return
				}
				let sendCode = {
					"mobile": this.loginFrom.phone,
					"smsmode": 0
				}
				index.getPublicMember(sendCode, 'sys/clientSms', 'post', res => {
					if (res.data.success) {
						index.show_tips('发送成功')
						this.sendDataShow = this.sendDataShow == true ? false : true;
						var sen = setInterval(() => {
							if (this.sendData <= 0) {
								this.sendData = 60
								this.sendDataShow = true
								clearInterval(sen)
							}
							this.sendData--
						}, 1000)
					} else {
						this.sendDataShow = true
						this.sendData = 60
						index.show_tips(res.data.message)
						return false
					}
				})

			},
			getMoble() {
				var numArray = new Array("939", "938", "937", "936", "935", "934", "959", "958", "957", "950", "951",
					"952", "988", "987", "982", "983", "984", "978", "930", "931", "932", "956", "955", "986", "985",
					"976", "933", "953", "989", "980", "981", "977");
				var numList = "";
				var arraryLength = numArray.length;
				var i = parseInt(Math.random() * arraryLength);
				var num = numArray[i];
				for (var j = 0; j < 8; j++) {
					num = num + Math.floor(Math.random() * 10);
				}
				return num;
			},
			// getLon() {
			// 	uni.getLocation({
			// 		type: 'wgs84',
			// 		success: (res) => {
			// 			this.currentCity.arealat = res.latitude
			// 			this.currentCity.arealon = res.longitude
			// 		},
			// 		fail: (err) => {
			// 			uni.getSetting({
			// 				success: (rs) => {
			// 					let status = rs.authSetting
			// 					if (!status['scope.userLocation']) {
			// 						uni.showModal({
			// 							title: '是否授权当前位置',
			// 							content: '需要获取您的地理位置，请确认授权，否则地图功能将无法开启',
			// 							success: (tip) => {
			// 								if (tip.confirm) {
			// 									uni.openSetting({
			// 										success: (data) => {
			// 											if (data
			// 												.authSetting[
			// 													'scope.userLocation'
			// 													] === true
			// 												) {
			// 												index
			// 													.show_tips(
			// 														'授权成功')
			// 												uni.getLocation({
			// 													type: 'wgs84',
			// 													success: (
			// 														nodes
			// 														) => {
			// 														this.currentCity
			// 															.arealat =
			// 															nodes
			// 															.latitude
			// 														this.currentCity
			// 															.arealon =
			// 															nodes
			// 															.longitude
			// 														// let url="./addMap?str="+JSON.stringify(this.xiangmu)+"&wxstring="+JSON.stringify(this.wxmap)
			// 														// index.navigate_to(url)
			// 													}
			// 												})
			// 											} else {
			// 												index
			// 													.show_tips(
			// 														'授权失败')
			// 												return false
			// 											}
			
			// 										}
			// 									})
			// 								}
			// 							}
			// 						})
			// 					} else {
			// 						uni.getLocation({
			// 							type: 'wgs84',
			// 							success: (nodes) => {
			// 								this.currentCity.arealat = nodes.latitude
			// 								this.currentCity.arealon = nodes.longitude
			// 								// let url="./addMap?str="+JSON.stringify(this.xiangmu)+"&wxstring="+JSON.stringify(this.wxmap)
			// 								// index.navigate_to(url)
			// 							}
			// 						})
			// 					}
			// 				},
			// 				fail: (noerr) => {
			// 					index.show_tips('调用授权窗口失败')
			// 					return false
			// 				}
			// 			})
			// 		}
			// 	})
			// }
		},
		onLoad(opt) {
			let deviceId;
			var pages = getCurrentPages() // 获取栈实例
			this.sourceUrl = pages[0].route; // 获取当前页面路由
			// this.getLon() //开启地图定位
			let that = this;
			uni.getSystemInfo({
				success(res) {
					if (res) {
						deviceId = res['deviceId'] ? res['deviceId'] : '';
					}
					that.deviceId = deviceId;
				},
				fail() {

				}
			})
			if (opt.url && opt.id) {
				this.backUrl = opt.url
				this.jobid = opt.id
			}
			this.getMoble();
		}

	}
</script>

<style>
	@import url("@/static/css/publics.css");
	@import url("@/static/css/login.css");
</style>